package com.ljc.utils;

import com.ljc.common.RedisTokenLimiter;
import com.ljc.constant.RedisConstant;
import com.ljc.model.dto.SmsDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 短信发送工具类
 */
@Component
@Slf4j
public class SmsUtils {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisTokenLimiter redisTokenLimiter;
    @Resource
    private SmsRabbitMqUtils rabbitMqUtils;

    /**
     * 发送验证码
     */
    public boolean sendSms(SmsDTO smsDTO) {
        // 从令牌桶中取得令牌，未取得不允许发送短信
        boolean acquire = redisTokenLimiter.tryAcquire(smsDTO.getPhoneNum());
        if (!acquire) {
            log.info("phoneNum：{}，send SMS frequent", smsDTO.getPhoneNum());
            return false;
        }
        log.info("发送短信：{}", smsDTO);
        String phoneNum = smsDTO.getPhoneNum();
        String code = smsDTO.getCode();

        // 将手机号对应的验证码存入Redis，方便后续检验
        stringRedisTemplate.opsForValue().set(RedisConstant.SMS_CODE_PREFIX + phoneNum, String.valueOf(code), 5, TimeUnit.MINUTES);

        rabbitMqUtils.sendSmsAsync(smsDTO);
        return true;
    }

    /**
     * 校验验证码
     */
    public boolean verifyCode(String phoneNum, String code) {
        String key = RedisConstant.SMS_CODE_PREFIX + phoneNum;
        String checkCode = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(code) && code.equals(checkCode)) {
            stringRedisTemplate.delete(key);
            return true;
        }
        return false;

    }
}